import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import {useLoginStore} from "@/stores/login";
import { useCategoryStore } from '@/stores/categoryStore';
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    meta: { requiresAuth: false },
    component: () => import('@/layouts/LoginPage.vue')
  },
  {
    path: '/',
    name: 'main',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect:'/hello',
    meta: { requiresAuth: true },
    children: [
      { path: 'hello', name: 'hello', component: () => import('@/views/hello.vue'),meta: { requiresAuth: true }  },
      { path: 'goods', name: 'Goods', component: () => import('@/views/goods/GoodsManagement.vue'),meta: { requiresAuth: true }  },
      { path: 'feedback', name: 'Feedback', component: () => import('@/views/feedback/FeedbackHandle.vue'),meta: { requiresAuth: true }  },
      { path: 'orders', name: 'Orders', component: () => import('@/views/orders/OrderManagement.vue'),meta: { requiresAuth: true }  },
      { path: 'statistics', name: 'Statistics', component: () => import('@/views/statistics/Dashboard.vue'),meta: { requiresAuth: true }  },
      { path: 'coupons', name: 'Coupons', component: () => import('@/views/coupons/CouponManagement.vue'),meta: { requiresAuth: true }  },
      { path: 'customer-service', name: 'CustomerService', component: () => import('@/views/customer/CustomerService.vue'),meta: { requiresAuth: true }  },
      { path: 'users', name: 'UserManagement', component: () => import('@/views/users/UserManagement.vue'),meta: { requiresAuth: true }  },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from,next) => {
  const requiresAuth = to.meta.requiresAuth; // 检查目标路由是否需要登录
  if (requiresAuth&&(localStorage.getItem("token")==null||localStorage.getItem("token")=="")) {
      next({ name: "login" });
  } else {
    const categoryStore = useCategoryStore();
    if (!categoryStore.isLoaded) {
      categoryStore.fetchCategories().then(() => console.log("OK"));
    }
    next();
  }
})

export default router
